package com.sgb.member.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityMemberAddclientBinding;
import com.sgb.member.di.DaggerMemberComponent;
import com.sgb.member.di.MemberModule;
import com.sgb.member.entity.BusinessTypeBean;
import com.sgb.member.entity.CompanyInfoEntity;
import com.sgb.member.entity.CompanyNatureEntity;
import com.sgb.member.entity.MemberAddClientBean;
import com.sgb.member.entity.MemberClientListBean;
import com.sgb.member.entity.MemberCompanyInfoEntity;
import com.sgb.member.entity.ServiceRangeBean;
import com.sgb.member.ui.adapter.CompanyNameAdapter;
import com.sgb.member.view_model.AddClientModel;
import com.swgk.core.base.AppActivity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.swgk.core.view.selection.CommonPopEntity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * Time:2021/8/26
 * AUTHOR:F_Q
 * Description:用户中心-会员-新增客户管理
 */
public class MemberAddClientActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    MemberAddClientBean bean = new MemberAddClientBean();
    private ActivityMemberAddclientBinding mMemberAddclient;
    @Inject
    AddClientModel model;
    //企业性质
    private List<CompanyNatureEntity> companyNatureList;
    //企业性质选择框
    private OptionsPickerView<CompanyNatureEntity> mOptionCompany;

    //经营类型
    private List<CommonPopEntity> managementTypes;
    //服务范围
    private List<CommonPopEntity> serviceArea;
    //搜索公司列表
    private CompanyNameAdapter adapter;
    //经营类型
    List<BusinessTypeBean> businesstypelist = new ArrayList<>();
    //服务范围
    List<ServiceRangeBean> ServiceRangelist = new ArrayList<>();
    //行业分类
    private List<CommonPopEntity> industrytypelist;
    //行业分类二级
    private List<List<CommonPopEntity>> opt2 = new ArrayList<>();
    // 三级联动数据
    private int cityPosition1;
    private int cityPosition2;
    private String lat;
    private String lot;
    private boolean isonclick = true; // 是否选择企业列表

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMemberComponent.builder()
                .appComponent(appComponent)
                .memberModule(new MemberModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        mMemberAddclient = DataBindingUtil.setContentView(this, R.layout.activity_member_addclient);
        MemberClientListBean clientBean = (MemberClientListBean) getIntent().getSerializableExtra("data");
        if (clientBean != null) {
            mMemberAddclient.companyName.setKeyListener(null);//不可粘贴
            mMemberAddclient.companyName.setClickable(false);//不可点击
            mMemberAddclient.companyName.setFocusable(false);//不可编辑
            mMemberAddclient.companyName.setEnabled(false);
            mMemberAddclient.title.titleView.setText("客户编辑");
            isonclick = false;
            //编辑回显
            EditData(clientBean);

        } else {
            mMemberAddclient.title.titleView.setText("新增客户");
            //监听企业名称输入
            mMemberAddclient.companyName.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    //获取相关企业信息列表
                    String name = s.toString().trim();
                    if(StringUtil.isEmpty(name)){
                        isonclick = true;
                        mMemberAddclient.recyclerview.setVisibility(View.GONE);
                    } else {
                        if (isonclick) {
                            model.getCompanyName(name);
                        } else {
                            isonclick = true;
                        }
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }
        mMemberAddclient.title.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ViewOnClick();//初始化点击事件
    }


    @Override
    protected void init() {
        super.init();
        lat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
        if (TextUtils.isEmpty(lat)) {
            lat = "0";
        }
        lot = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
        if (TextUtils.isEmpty(lot)) {
            lot = "0";
        }


    }

    /**
     * 初始化点击事件
     */
    private void ViewOnClick() {
        //企业性质
        mMemberAddclient.companyNature.setOnWholeItemClickListener(this);
        //行业类型
        mMemberAddclient.industryType.setOnWholeItemClickListener(this);
        //经营类型
        mMemberAddclient.managementTypes.setOnWholeItemClickListener(this);
        //服务范围
        mMemberAddclient.serviceArea.setOnWholeItemClickListener(this);
        //经营地址
        mMemberAddclient.businessAddress.setOnWholeItemClickListener(this);
        //提交
        mMemberAddclient.submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitData();
            }
        });
    }

    //提交数据信息
    private void submitData() {
        if (TextUtils.isEmpty(mMemberAddclient.companyName.getText().toString().trim())) {
            MToast.showToast(this, "请输入企业名称");
            return;
        } else {
            bean.setCompanyName(mMemberAddclient.companyName.getText().toString().trim());
        }
        if (TextUtils.isEmpty(mMemberAddclient.companyNature.getContent())) {
            MToast.showToast(this, "请选择企业性质");
            return;
        }
        if (TextUtils.isEmpty(mMemberAddclient.industryType.getContent())) {
            MToast.showToast(this, "请选择行业类型");
            return;
        }
        if (TextUtils.isEmpty(mMemberAddclient.managementTypes.getContent())) {
            MToast.showToast(this, "请选择经营类型");
            return;
        }
        if (TextUtils.isEmpty(mMemberAddclient.serviceArea.getContent())) {
            MToast.showToast(this, "请选择服务范围");
            return;
        }
        if (TextUtils.isEmpty(mMemberAddclient.businessAddress.getContent())) {
            MToast.showToast(this, "请选择经营地址");
            return;
        }
        if (TextUtils.isEmpty(mMemberAddclient.companyContact.getContent())) {
            MToast.showToast(this, "请填写联系人姓名");
            return;
        } else {
            bean.setContact(mMemberAddclient.companyContact.getContent());
        }
        if (TextUtils.isEmpty(mMemberAddclient.companyPhone.getContent())) {
            MToast.showToast(this, "请填写联系电话");
            return;
        } else {
            bean.setPhone(mMemberAddclient.companyPhone.getContent());
        }
        //调用提交接口
        model.getsaveOrUpdate(bean);
    }

    @Override
    public void OnWholeItemClick(View view) {
        if (view.getId() == R.id.company_nature) {//企业性质
            if (companyNatureList == null) {
                model.getCompanyNatureList();
            } else {
                showCompanyNaturePop("选择企业性质", companyNatureList);
            }
        } else if (view.getId() == R.id.industry_type) {//行业类型
            model.getIndustryTypeList();
        } else if (view.getId() == R.id.management_types) {//经营类型
            ChooseMemberTypeActivity.start(this, managementTypes, "34", MemberConfig.REQ_MANAGEMENT_TYPE);
        } else if (view.getId() == R.id.service_area) {//服务范围
            ChooseMemberTypeActivity.start(this, serviceArea, "35", MemberConfig.REQ_SERVICE_TYPE);
        } else if (view.getId() == R.id.business_address) {
            Intent intent = new Intent();
            intent.setClass(this, MemberMapActivity.class);
            intent.putExtra(MemberMapActivity.TITLE, "经营地址");
            intent.putExtra(MemberMapActivity.HINT, "请输入地址");
            intent.putExtra(MemberMapActivity.SAVE_TEXT, "确定");
            intent.putExtra(MemberMapActivity.LATITUDE, Double.parseDouble(lat));
            intent.putExtra(MemberMapActivity.LONGTITUDE, Double.parseDouble(lot));
            startActivityForResult(intent, MemberConfig.REQ_MAP);
        }
    }

    /**
     * 编辑回显
     *
     * @param clientBean
     */
    private void EditData(MemberClientListBean clientBean) {
        //企业名称
        mMemberAddclient.companyName.setText(clientBean.getCompanyName());
        bean.setCompanyNo(clientBean.getCompanyNo());
        bean.setNo(clientBean.getNo());
        //企业性质
        mMemberAddclient.companyNature.setContent(clientBean.getCompanyAttribute());
        bean.setCompanyAttribute(clientBean.getCompanyAttribute());
        bean.setCompanyAttributeNo(clientBean.getCompanyAttributeNo());
        //行业类型一级
        if (!TextUtils.isEmpty(clientBean.getTradeTypeFirst())) {
            mMemberAddclient.industryType.setContent(clientBean.getTradeTypeFirst());
            bean.setTradeTypeFirst(clientBean.getTradeTypeFirst());
            bean.setTradeTypeFirstNo(clientBean.getTradeTypeFirstNo() + "");
        }
        //行业类型二级
        if (!TextUtils.isEmpty(clientBean.getTradeTypeSecond())) {
            String content = mMemberAddclient.industryType.getContent();
            mMemberAddclient.industryType.setContent(content + "/" + clientBean.getTradeTypeSecond());
            bean.setTradeTypeSecond(clientBean.getTradeTypeSecond());
            bean.setTradeTypeSecondNo(clientBean.getTradeTypeSecondNo() + "");
        }
        //经营类型
        List<MemberClientListBean.businessTypeBean> businessType = clientBean.getBusinessType();
        if (businessType != null && businessType.size() > 0) {
            List<CommonPopEntity> servicelist = new ArrayList<>();
            StringBuilder sb = new StringBuilder();
            for (MemberClientListBean.businessTypeBean businessTypeBean : businessType) {
                sb.append(businessTypeBean.getName()).append(",");
                CommonPopEntity comm = new CommonPopEntity();
                comm.setTypeName(businessTypeBean.getName() + "");
                comm.setCode(businessTypeBean.getCode() + "");
                servicelist.add(comm);
            }
            String str = sb.substring(0, sb.toString().length() - 1);
            mMemberAddclient.managementTypes.setContent(str);
            managementTypes = servicelist;
            bean.setBusinessType(new Gson().toJson(businessType));
        } else {
            mMemberAddclient.managementTypes.setContent("");
            bean.setBusinessType("");
        }
        //服务范围
        List<MemberClientListBean.serviceRangeBean> serviceRange = clientBean.getServiceRange();
        if (serviceRange != null && serviceRange.size() > 0) {
            List<CommonPopEntity> servicecomm = new ArrayList<>();
            StringBuilder sb = new StringBuilder();
            for (MemberClientListBean.serviceRangeBean serviceRangeBean : serviceRange) {
                sb.append(serviceRangeBean.getName()).append(",");
                CommonPopEntity comm = new CommonPopEntity();
                comm.setTypeName(serviceRangeBean.getName() + "");
                comm.setId(serviceRangeBean.getId());
                servicecomm.add(comm);
            }
            String str = sb.substring(0, sb.toString().length() - 1);
            mMemberAddclient.serviceArea.setContent(str);
            serviceArea = servicecomm;
            bean.setServiceRange(new Gson().toJson(serviceRange));
        } else {
            mMemberAddclient.serviceArea.setContent("");
            bean.setServiceRange("");
        }
        //经营地址
        mMemberAddclient.businessAddress.setContent(clientBean.getBusinessAddress() + "");
        bean.setBusinessAddress(clientBean.getBusinessAddress() + "");
        if (!TextUtils.isEmpty(clientBean.getLatitude())){
            lat = clientBean.getLatitude();
        }else {
            lat = "0";
        }
        if (!TextUtils.isEmpty(clientBean.getLongitude())){
            lot = clientBean.getLongitude();
        }else {
            lot = "0";
        }
        bean.setLatitude(lat + "");
        bean.setLongitude(lot + "");
        //联系人
        mMemberAddclient.companyContact.setContent(clientBean.getContact());
        //联系电话
        mMemberAddclient.companyPhone.setContent(clientBean.getPhone());
    }

    /**
     * 企业性质选择
     *
     * @param title
     * @param companyNatureList
     */
    private void showCompanyNaturePop(String title, List<CompanyNatureEntity> companyNatureList) {
        if (mOptionCompany == null) {
            mOptionCompany = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                mMemberAddclient.companyNature.setContent(companyNatureList.get(options1).getName());
                bean.setCompanyAttribute(companyNatureList.get(options1).getName());
                bean.setCompanyAttributeNo(companyNatureList.get(options1).getId() + "");
            }).setCancelColor(getResources().getColor(R.color.color_title_small)).build();
        }
        mOptionCompany.setTitleText(title);
        mOptionCompany.setPicker(companyNatureList);
        mOptionCompany.setSelectOptions(0);
        mOptionCompany.show();
    }

    /**
     * 企业性质List
     *
     * @param data
     */
    public void setCompanyNatureList(List<CompanyNatureEntity> data) {
        this.companyNatureList = data;
        showCompanyNaturePop("选择企业性质", companyNatureList);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        //经营类型
        if (resultCode == RESULT_OK && requestCode == MemberConfig.REQ_MANAGEMENT_TYPE) {
            managementTypes = (List<CommonPopEntity>) intent.getSerializableExtra("MEMBER_DATA");
            if (managementTypes != null && managementTypes.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (CommonPopEntity memberType : managementTypes) {
                    businesstypelist.add(new BusinessTypeBean(memberType.getTypeName(), memberType.getCode()));
                    sb.append(memberType.getTypeName()).append(",");
                }
                String str = sb.substring(0, sb.toString().length() - 1);
                mMemberAddclient.managementTypes.setContent(str);
                bean.setBusinessType(new Gson().toJson(businesstypelist));
            } else {
                mMemberAddclient.managementTypes.setContent("");
                bean.setBusinessType("");
            }
        }
        //服务范围
        if (resultCode == RESULT_OK && requestCode == MemberConfig.REQ_SERVICE_TYPE) {
            serviceArea = (List<CommonPopEntity>) intent.getSerializableExtra("MEMBER_DATA");
            if (serviceArea != null && serviceArea.size() > 0) {
                StringBuilder sb = new StringBuilder();
                for (CommonPopEntity memberType : serviceArea) {
                    ServiceRangelist.add(new ServiceRangeBean(memberType.getId() + "", memberType.getTypeName()));
                    sb.append(memberType.getTypeName()).append(",");
                }
                String str = sb.substring(0, sb.toString().length() - 1);
                mMemberAddclient.serviceArea.setContent(str);
                bean.setServiceRange(new Gson().toJson(ServiceRangelist));
            } else {
                mMemberAddclient.serviceArea.setContent("");
                bean.setServiceRange("");
            }
        }
        if (resultCode == RESULT_OK && requestCode == MemberConfig.REQ_MAP) {
            double lat = intent.getDoubleExtra(MemberMapActivity.LATITUDE, 0);
            double lon = intent.getDoubleExtra(MemberMapActivity.LONGTITUDE, 0);
            String address = intent.getStringExtra(MemberMapActivity.CURRENT_POSITION);
            mMemberAddclient.businessAddress.setContent(address + "");
            bean.setBusinessAddress(address + "");
            bean.setLatitude(lat + "");
            bean.setLongitude(lon + "");
        }
    }

    /**
     * 企业列表筛选
     *
     * @param data
     */
    public void setCompanyNameList(List<MemberCompanyInfoEntity> data) {
        mMemberAddclient.recyclerview.setVisibility(View.VISIBLE);
        adapter = new CompanyNameAdapter(this, data);
        mMemberAddclient.recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        mMemberAddclient.recyclerview.setAdapter(adapter);
        adapter.setOnItemClick(new AdapterOnItemClick<MemberCompanyInfoEntity>() {
            @Override
            public void onItemClick(MemberCompanyInfoEntity entity, int position) {
                isonclick = false;
                model.loadCompanyData.setValue(false);
                mMemberAddclient.recyclerview.setVisibility(View.GONE);
                mMemberAddclient.companyName.setText(entity.getCompanyName());
                bean.setCompanyNo(entity.getCompanyNo());
                //测试存在compayNo为null
                if (!TextUtils.isEmpty(entity.getCompanyNo())) {
                    model.getDetailsByCompany(entity.getCompanyNo());
                }
            }
        });
    }

    /**
     * 行业类型
     *
     * @param data
     */
    public void setIndustryTypeList(List<CommonPopEntity> data) {
        this.industrytypelist = data;
        for (int i = 0; i < industrytypelist.size(); i++) {
            if (industrytypelist.get(i).getChildren() != null) {
                opt2.add(industrytypelist.get(i).getChildren());
            } else {
                opt2.add(new ArrayList<>());
            }
        }
        if (industrytypelist != null && industrytypelist.size() > 0) {
            showIndustryTypePop();
        }
    }

    /**
     * 行业pop
     */
    private void showIndustryTypePop() {
        CityPickView cityOption = new CityPickBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (!TextUtils.isEmpty(opt2.get(options1).get(options2).getTypeName())) {
                    mMemberAddclient.industryType.setContent(industrytypelist.get(options1).getTypeName() + "/" + opt2.get(options1).get(options2).getTypeName());
                    bean.setTradeTypeFirst(industrytypelist.get(options1).getTypeName());
                    bean.setTradeTypeFirstNo(industrytypelist.get(options1).getId());
                    bean.setTradeTypeSecond(opt2.get(options1).get(options2).getTypeName());
                    bean.setTradeTypeSecondNo(opt2.get(options1).get(options2).getId());
                } else {
                    mMemberAddclient.industryType.setContent(industrytypelist.get(options1).getTypeName());
                    bean.setTradeTypeFirst(industrytypelist.get(options1).getTypeName());
                    bean.setTradeTypeFirstNo(industrytypelist.get(options1).getId());
                    bean.setTradeTypeSecond("");
                    bean.setTradeTypeSecondNo("");
                }
            }
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("选择行业类型")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .build();
        cityOption.setPicker(industrytypelist, opt2);
        cityOption.setSelectOptions(cityPosition1, cityPosition2);
        cityOption.show();
    }

    //成功后的处理
    public void onSuccess() {
        setResult(RESULT_OK, new Intent());
        finish();
    }

    /**
     * 根据公司no查询的公司信息
     *
     * @param data
     */
    public void setDetailsByCompany(CompanyInfoEntity data) {
        //企业性质
        mMemberAddclient.companyNature.setContent(data.getCompanyQualityName());
        bean.setCompanyAttribute(data.getCompanyQualityName());
        bean.setCompanyAttributeNo(data.getCompanyQualityNo());
        //行业类型一级
        if (!TextUtils.isEmpty(data.getIndustryCategoryOneName())) {
            mMemberAddclient.industryType.setContent(data.getIndustryCategoryOneName());
            bean.setTradeTypeFirst(data.getIndustryCategoryOneName());
            bean.setTradeTypeFirstNo(data.getIndustryCategoryOneId() + "");
        }
        //行业类型二级
        if (!TextUtils.isEmpty(data.getIndustryCategoryTwoName())) {
            String content = mMemberAddclient.industryType.getContent();
            mMemberAddclient.industryType.setContent(content + "/" + data.getIndustryCategoryTwoName());
            bean.setTradeTypeSecond(data.getIndustryCategoryTwoName());
            bean.setTradeTypeSecondNo(data.getIndustryCategoryTwoId() + "");
        }
        //经营类型
        if (!TextUtils.isEmpty(data.getServiceTypeName())) {
            String[] ServiceTypeName = data.getServiceTypeName().split(",");//经营类型名称数组
            String[] ServiceType = data.getServiceType().split(",");//经营类型id数组
            List<CommonPopEntity> servicelist = new ArrayList<>();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < ServiceTypeName.length; i++) {
                sb.append(ServiceTypeName[i]).append(",");
                CommonPopEntity comm = new CommonPopEntity();
                comm.setTypeName(ServiceTypeName[i] + "");
                if (!TextUtils.isEmpty(ServiceType[i])) {
                    comm.setCode(ServiceType[i] + "");
                }
                servicelist.add(comm);
            }
            String str = sb.substring(0, sb.toString().length() - 1);
            mMemberAddclient.managementTypes.setContent(str);
            managementTypes = servicelist;
            List<BusinessTypeBean>  businessTypeBeans = new ArrayList<>();
            for (CommonPopEntity commonPopEntity : servicelist) {
                businessTypeBeans.add(new BusinessTypeBean(commonPopEntity.getTypeName(),commonPopEntity.getCode()));
            }
            bean.setBusinessType(new Gson().toJson(businessTypeBeans));
        } else {
            mMemberAddclient.managementTypes.setContent("");
            bean.setBusinessType("");
        }
        //服务范围
        List<CompanyInfoEntity.ServiceAreaDTO> service = data.getServiceArea();
        if (service != null && service.size() > 0) {
            List<CommonPopEntity> servicecomm = new ArrayList<>();
            StringBuilder sb = new StringBuilder();
            for (CompanyInfoEntity.ServiceAreaDTO serviceAreaDTO : service) {
                sb.append(serviceAreaDTO.getName()).append(",");
                CommonPopEntity comm = new CommonPopEntity();
                comm.setTypeName(serviceAreaDTO.getName() + "");
                comm.setId(serviceAreaDTO.getId());
                servicecomm.add(comm);
            }
            String str = sb.substring(0, sb.toString().length() - 1);
            mMemberAddclient.serviceArea.setContent(str);
            serviceArea = servicecomm;
            bean.setServiceRange(new Gson().toJson(service));
        } else {
            mMemberAddclient.serviceArea.setContent("");
            bean.setServiceRange("");
        }
        //经营地址
        mMemberAddclient.businessAddress.setContent(data.getMapAddress() + "");
        bean.setBusinessAddress(data.getMapAddress() + "");
        if (!TextUtils.isEmpty(data.getLatitude())){
            lat = data.getLatitude();
        }else {
            lat = "0";
        }
        if (!TextUtils.isEmpty(data.getLongitude())){
            lot = data.getLongitude();
        }else {
            lot = "0";
        }
        bean.setLatitude(lat + "");
        bean.setLongitude(lot + "");
        //联系人
        mMemberAddclient.companyContact.setContent(data.getConcat());
        //联系电话
        mMemberAddclient.companyPhone.setContent(data.getPhone());

    }
}
